package com.jiuzhe.commercial.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.CalendarBean;
import com.jiuzhe.commercial.bean.TakeAccountResult;
import com.jiuzhe.commercial.bean.TakeMoneyParams;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient2;
import com.jiuzhe.commercial.utils.DESUtil;
import com.jiuzhe.commercial.utils.RandomUtil;
import com.jiuzhe.commercial.utils.RxBus;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;
import com.jungly.gridpasswordview.GridPasswordView;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by huanghao on 2018/5/24.
 * 提现
 */

public class WithdrawActivity extends BaseActivity {
    @BindView(R.id.rl_zhifubao)
    RelativeLayout rlZhifubao;
    @BindView(R.id.tv_money)
    EditText tvMoney;
    @BindView(R.id.bt_ok)
    Button btOk;
    @BindView(R.id.tv_withdraw)
    TextView tvWithdraw;
    @BindView(R.id.tv_accounts_name)
    TextView tvAccountsName;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_loose) //帐户余额
            TextView tvLoose;
    private String mAccountName;
    private String mAccount, mMoney;
    private View mView;
    private String mID;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_withdraw);
        setTitle("提现");
    }

    @Override
    protected void loadData() {
        if(Constants.TOTALMONEY != null)
        tvLoose.setText("零钱余额 ￥" + Constants.TOTALMONEY);
        String name = SPUtil.getString(this,"name");
        if (!TextUtils.isEmpty(name)){
            tvAccountsName.setText(name);
        }
        String account = SPUtil.getString(this,"account");
        if (!TextUtils.isEmpty(account)){
            tvAccount.setText(account);
        }
    }

    @OnClick({R.id.rl_zhifubao, R.id.tv_withdraw, R.id.bt_ok})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_zhifubao:
                Intent intent = new Intent(WithdrawActivity.this, ZhiFuBaoActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_withdraw:
                tvMoney.setText(Constants.TOTALMONEY);
                tvMoney.setSelection(Constants.TOTALMONEY.length());
                break;
            case R.id.bt_ok:
                confirm();
                break;
        }
    }

    /**
     * 确认
     */
    private void confirm() {
        mAccountName = tvAccountsName.getText().toString().trim();
        mAccount = tvAccount.getText().toString().trim();
        mMoney = tvMoney.getText().toString().trim();
        if (TextUtils.isEmpty(mAccountName)) {
            UIUtils.showToastSafe("请输入支付宝帐号人名");
            return;
        }
        if (TextUtils.isEmpty(mAccount)) {
            UIUtils.showToastSafe("请输入支付宝帐号");
            return;
        }
        if (TextUtils.isEmpty(mMoney)) {
            UIUtils.showToastSafe("请输入提现金额");
            return;
        }
        int intMoney = (int) (Double.valueOf(mMoney) * 100);
        if (intMoney<=0){
            UIUtils.showToastSafe("提现金额需大于0");
            return;
        }
        inPutPassWord();
    }

    /**
     * 输入支付密码
     */
    private void inPutPassWord() {
        final Dialog alertDialog = new Dialog(this, R.style.EasyListDialogStyle);
        mView = LayoutInflater.from(this).inflate(R.layout.order_input_pwd, null);
        alertDialog.setContentView(mView);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        window.setAttributes(lp);
        GridPasswordView gridPasswordView = mView.findViewById(R.id.pswView);
        gridPasswordView.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {

            }

            @Override
            public void onInputFinish(String psw) {
                generateId(psw, alertDialog);
            }
        });
    }

    /**
     * 交易之前生成id
     *
     * @param psw
     * @param alertDialog
     */
    private void generateId(final String psw, final Dialog alertDialog) {
        HashMap<String, String> map = new HashMap<>();
        mID = SPUtil.getString(WithdrawActivity.this, Constants.ID);
        String token = SPUtil.getString(WithdrawActivity.this, Constants.TOKEN);
        String autoSignStr = Constants.GENERATEID.substring(Constants.GENERATEID.lastIndexOf("0/") + 1)  + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        String url = Constants.GENERATEID   + "?token=" + mID + "&&sign=" + signStr;
        HttpClient2.get(this, url, map, new CallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> strList) {
                if (strList.get(0).equals("39")) {
                    String generateId = strList.get(2);
                    takeMoney(generateId, psw, alertDialog);
                }
            }
        });
    }

    /**
     * 提现
     *
     * @param generateId
     * @param psw
     * @param alertDialog
     */
    private void takeMoney(String generateId, final String psw, final Dialog alertDialog) {
        HashMap<String, String> map = new HashMap<>();
        String mer_id = SPUtil.getString(WithdrawActivity.this, Constants.MERCHANTID);
        TakeMoneyParams takeMoneyParams = new TakeMoneyParams();
        takeMoneyParams.setId(generateId);
        takeMoneyParams.setAmount((int)(Double.valueOf(mMoney)*100) +"");
        takeMoneyParams.setChannel("alipay");
        takeMoneyParams.setDescription("玖折账户提现");
        takeMoneyParams.setFee("");
        takeMoneyParams.setUser_from(mer_id);
        takeMoneyParams.setSettle_account_id(SPUtil.getString(WithdrawActivity.this,"take_id"));

        String mingwenPwd = psw + mID.substring(3,10);
        String miwenPayPwd = UIUtils.Md5(mingwenPwd);
        takeMoneyParams.setPasswd(miwenPayPwd);
        /**
         * 参数加密
         */
        String partKey = RandomUtil.getRandomNumbersAndLetters(12);
        String key = partKey + Constants.PARTKEY;
        String miwen = DESUtil.encode(key, JSON.toJSONString(takeMoneyParams));

        String token = SPUtil.getString(WithdrawActivity.this, Constants.TOKEN);
        String autoSignStr = Constants.TAKEMONEY.substring(Constants.TAKEMONEY.lastIndexOf("0/") + 1) + "/" + partKey + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);

        map.put("data",miwen);
        map.put("token",mID);
        map.put("sign",signStr);

        HttpClient2.post(this, Constants.TAKEMONEY + "/" + partKey, map, new CallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> stringList) {
                if (stringList.get(0).equals("45")) { //提现成功
                    alertDialog.dismiss();
                    UIUtils.showToastSafe(stringList.get(1));
                    RxBus.getInstance().post(new CalendarBean());
                    finish();
                }
                if(stringList.get(0).equals("44")){
                    alertDialog.dismiss();
                    UIUtils.showToastSafe(stringList.get(2));
                }
                if(stringList.get(0).equals("4")){
                    UIUtils.showToastSafe(stringList.get(1));
                    alertDialog.dismiss();
                }
                if(stringList.get(0).equals("9")){
                    UIUtils.showToastSafe(stringList.get(1));
                    alertDialog.dismiss();
                }
                if(stringList.get(0).equals("12")){
                    UIUtils.showToastSafe(stringList.get(1));
                    alertDialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    String name = data.getStringExtra("name");
                    String account = data.getStringExtra("account");
                    SPUtil.put(this,"name",name);
                    SPUtil.put(this,"account",account);
                    tvAccountsName.setText(name);
                    tvAccount.setText(account);
                    getSettleaccount();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 得到帐户信息
     */
    private void getSettleaccount() {
        HashMap<String, String> map = new HashMap<>();
        String id = SPUtil.getString(this, Constants.ID);
        String mr_id = SPUtil.getString(this, Constants.MERCHANTID);
        String token = SPUtil.getString(this, Constants.TOKEN);
        String autoSignStr = Constants.GETSETTLEACCOUNT.substring(Constants.GETSETTLEACCOUNT.lastIndexOf("0/")+1)  + mr_id + "/alipay?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);

        String url = Constants.GETSETTLEACCOUNT  + mr_id + "/alipay?token=" + id + "&&sign=" + signStr;

        HttpClient2.get(this, url , map, new CallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> result){
                if(result.get(0).equals("31")){//查询成功
                    List<TakeAccountResult> takeAccountResultList = JSON.parseArray(result.get(2), TakeAccountResult.class);
                    SPUtil.put(WithdrawActivity.this,"take_id",takeAccountResultList.get(0).getId());
                }
            }
        });
    }
}
